/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/

// 思路：
// 首先明确promise内需要填写的内容
// 1 先设置三个状态
// 2 构造函数里要写try catch 记录成功和失败
// 3 定义五个初始值 分别是status value reason successCallback failCallback
// 4 明确 普通方法--5个  静态方法--2个
// 分别是 resolve reject then finally catch
//        all resolve


//==============  想明白思路后手写 最后对过老师答案进行修改 下方非全部手写  =====================


//  3个状态
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';

class MyPromise {
    // 构造函数里用tye catch
    constructor(executor) {
        try {
            executor(this.resolve, this.reject)
        } catch (e) {
            this.reject(e);
        }
    }

    // 定义五个初始值
    status = PENDING;
    value = undefined;
    reason = undefined;
    successCallback = [];
    failCallback = [];

    resolve = value => {
        //判断状态是否是pending 如果是 那就return出去
        if (this.status !== PENDING) return;
        // 不是pending 那就成功 把状态修改并保存值
        this.status = FULFILLED;
        this.value = value;
        // 调用成功回调继续向下走
        // 先判断成功回调有没有
        this.successCallback && this.successCallback(this.value);
    }

    reject = reason => {
        //判断状态是否是pending 如果是 那就return出去
        if (this.status !== PENDING) return;
        // 不是pending 那就失败 把状态修改并保存原因
        this.status = REJECTED;
        this.reason = reason;
        // 调用失败回调
        // 先判断失败回调有没有
        this.failCallback && this.failCallback(this.reason);
    }
    // then中有两个参数 分别是成功回调和失败回调
    then(successCallback, failCallback) {
        // 成功 拿上一步给下来的值
        successCallback = successCallback ? successCallback : value => value;
        // 失败 记录失败原因
        failCallback = failCallback ? failCallback : reason => { throw reason };
        let promsie2 = new MyPromise((resolve, reject) => {
            // 判断status状态
            // 成功
            if (this.status === FULFILLED) {
                setTimeout(() => {
                    try {
                        let x = successCallback(this.value);
                        resolvePromise(promsie2, x, resolve, reject)
                    } catch (e) {
                        reject(e);
                    }
                }, 0)
                // 失败
            } else if (this.status === REJECTED) {
                setTimeout(() => {
                    try {
                        let x = failCallback(this.reason);
                        resolvePromise(promsie2, x, resolve, reject)
                    } catch (e) {
                        reject(e);
                    }
                }, 0)
                // pendding状态 此时将两种回调都储存起来 等待结果
            } else {
                this.successCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = successCallback(this.value);
                            resolvePromise(promsie2, x, resolve, reject)
                        } catch (e) {
                            reject(e);
                        }
                    }, 0)
                });
                this.failCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = failCallback(this.reason);
                            resolvePromise(promsie2, x, resolve, reject)
                        } catch (e) {
                            reject(e);
                        }
                    }, 0)
                });
            }
        });
        return promsie2;
    }
    // 取到最后的值 同样也有成功和失败两种
    finally(callback) {
        return this.then(value => {
            return MyPromise.resolve(callback()).then(() => value);
        }, reason => {
            return MyPromise.resolve(callback()).then(() => { throw reason })
        })
    }
    // 捕获失败
    catch(failCallback) {
        return this.then(undefined, failCallback)
    }
    // 将所有的都执行完
    static all(array) {
        let result = [];
        // 定义一个index 每执行一次就++
        let index = 0;
        return new MyPromise((resolve, reject) => {
            function addData(key, value) {
                result[key] = value;
                index++;
                // 看index的值和数组的长度是否相等 如果相等了 那就是执行完毕了
                if (index === array.length) {
                    resolve(result);
                }
            }
            for (let i = 0; i < array.length; i++) {
                let current = array[i];
                // 用instanceof判断这个值是promise对象还是普通值
                if (current instanceof MyPromise) {
                    current.then(value => addData(i, value), reason => reject(reason))
                } else {
                    addData(i, array[i]);
                }
            }
        })
    }
    static resolve(value) {
        if (value instanceof MyPromise) return value;
        return new MyPromise(resolve => resolve(value));
    }
}